package com.sayyi.demo.micro.order.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.sayyi.demo.micro.order.convertor.OrderConvertor;
import com.sayyi.demo.micro.order.entity.OrderTbl;
import com.sayyi.demo.micro.order.mapper.OrderTblMapper;
import com.sayyi.demo.micro.order.service.OrderTccService;
import com.sayyi.demo.micro.storage.api.StorageApi;
import com.sayyi.demo.micro.storage.domain.UpdateStorageRequest;
import io.seata.rm.tcc.api.BusinessActionContext;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
public class OrderTccServiceImpl implements OrderTccService {

    @DubboReference(version = "1.0.0")
    private StorageApi storageApi;

    @Autowired
    private OrderConvertor orderConvertor;

    @Autowired
    private OrderTblMapper orderTblMapper;


    @Override
    @Transactional
    public int createOrder(BusinessActionContext actionContext, OrderTbl orderTbl) {
        // 添加事务注解，让数据库来回滚
        orderTblMapper.insert(orderTbl);
        UpdateStorageRequest request = orderConvertor.orderToStorageRequest(orderTbl);
        storageApi.updateByTcc(request);
        return orderTbl.getId();
    }

    @Override
    public void commit(BusinessActionContext actionContext) {
        OrderTbl orderTbl = ((JSONObject) actionContext.getActionContext("orderTbl")).toJavaObject(OrderTbl.class);
        log.info("订单提交 [{}]", orderTbl);
    }

    @Override
    public void rollback(BusinessActionContext actionContext) {
        OrderTbl orderTbl = ((JSONObject) actionContext.getActionContext("orderTbl")).toJavaObject(OrderTbl.class);
        log.info("订单回滚 [{}]", orderTbl);
    }
}
